import { useSetState } from "react-use";
import { ResBody, request } from "../common/request";
import InfiniteScroll, {
  InfiniteScrollLoading,
} from "../components/InfiniteScroll";
import { GoodsCard } from "../components/GoodsCard";
import { GoodsModel } from "../common/model";
import { useCallback, useEffect } from "react";
import { useAuthStore } from "../store/auth";
import { useSystemStore } from "../store/system";
import { Masonry } from "../components/Masonry";
import { ScrollRestoration } from "react-router-dom";

const Find: React.FC = () => {
  const [state, setState] = useSetState({
    page: 1,
    data: [] as GoodsModel[],
    total: -1,
    loading: false as InfiniteScrollLoading,
  });
  const auth = useAuthStore();
  const system = useSystemStore();

  useEffect(() => {
    //先加载历史数据
    next(true);
  }, [auth.user, system.search]);

  const next = useCallback(
    async (init?: boolean) => {
      setState({ loading: init ? "reload" : "loadmore" });
      let page = init ? 1 : state.page;
      const ret = await request.get<any, ResBody>("/api/goods/query", {
        params: {
          page,
          page_size: 10,
          search: system.search,
        },
      });

      if (ret.code === 200) {
        setState((e) => ({
          data: init ? ret.goods : e.data.concat(ret.goods),
          total: ret.total,
          page: page + 1,
          loading: false,
        }));
      } else {
        setState({ loading: false });
      }
    },
    [state.page, system.search]
  );

  return (
    <div>
      <InfiniteScroll
        loading={state.loading}
        next={next}
        hasMore={state.total - state.data.length > 0}
        threshold={50}
        total={state.total}
      >
        <Masonry
          columns={{ default: 2, 500: 2, 1000: 3 }}
          gap={15}
          cellObserver
        >
          {state.data.map((d) => (
            <GoodsCard
              key={d.id}
              data={d}
              onLikeSwitch={(gid, liked_id) => {
                setState({
                  data: state.data.map((d) =>
                    d.id === gid
                      ? {
                          ...d,
                          like_count: liked_id
                            ? d.like_count + 1
                            : d.like_count - 1,
                          liked_id,
                        }
                      : d
                  ),
                });
              }}
            />
          ))}
        </Masonry>
      </InfiniteScroll>
      <ScrollRestoration />
    </div>
  );
};

export default Find;
